import type { MessageType } from "./message-context"

// 创建一个全局引用
let messageInstance: {
    addMessage: (type: MessageType, content: string, duration?: number) => void
    removeMessage: (id: string) => void
} | null = null

// 设置消息实例
export const setMessageInstance = (instance: {
    addMessage: (type: MessageType, content: string, duration?: number) => void
    removeMessage: (id: string) => void
}) => {
    messageInstance = instance
}

// 检查消息实例
const checkInstance = () => {
    if (!messageInstance) {
        console.warn("Message instance not found. Make sure MessageProvider is mounted.")
        return false
    }
    return true
}

// 消息API
const message = {
    success: (content: string, duration?: number) => {
        if (checkInstance()) {
            messageInstance!.addMessage("success", content, duration)
        }
    },
    error: (content: string, duration?: number) => {
        if (checkInstance()) {
            messageInstance!.addMessage("error", content, duration)
        }
    },
    warning: (content: string, duration?: number) => {
        if (checkInstance()) {
            messageInstance!.addMessage("warning", content, duration)
        }
    },
    info: (content: string, duration?: number) => {
        if (checkInstance()) {
            messageInstance!.addMessage("info", content, duration)
        }
    },
}

export default message

